var express = require("express");
var router = express.Router();
var conection = require("../db/sql.js");
var user = require("../db/userSql.js");
//引入
var QcloudSms = require("qcloudsms_js");

//引入jwt Token包
const jwt = require("jsonwebtoken");
// const { connect } = require("../db/sql.js");

//引入支付宝配置文件
const alipaySdk = require("../db/alipay.js");
const AlipayFormData = require("alipay-sdk/lib/form").default;

//引入axios
const axios = require("axios");

//判断过期时间函数
function getTimeToken(dataToken) {
  let tokenObj = jwt.decode(`${dataToken.token}`);

  let past = null;

  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      if (error) throw error;

      let token = results[0].token;

      let secret = dataToken;

      let past = null;

      jwt.verify(token, secret, (err, payload) => {
        console.log("token", token);
        console.log("secret", secret);
        console.log("payload", err);
        console.log("payload", payload);
        if (err) {
          past = true; //已经过期
        } else {
          // res.send({
          //     code:200,
          //     msg:'验证成功',
          //     payload
          // })
          past = false; //未过期
        }
      });
    }
  );
  return past;

  // //当前时间戳
  // let getTime = parseInt( new Date().getTime() / 1000);

  // console.log('getTime',getTime,'exp',exp)
  // console.log('getTime - exp:',getTime - exp)
  // console.log('========')
  // //时间超过60秒，表示已经过期
  // if( getTime - exp > 1000 ){
  //   console.log('getTime',getTime,'exp',exp)
  //   console.log('getTime - exp:',getTime - exp)
  //    return true
  // }
}

/* GET home page. */
router.get("/", function (req, res) {
  res.render("index", { title: "Express" });
});

//检验token
router.post("/api/chackToken", function (req, res) {
  console.log("check");
  let headers = req.headers;
  let token = headers["authorization"];
  var mi = "sdsadsadadsagfghgh";
  // let token = headers['authorization'];

  console.log("token:", token);

  jwt.verify(token, mi, (err, payload) => {
    console.log("theErr:", err);
    if (err) res.sendStatus(400);

    console.log(payload);
    if (payload) {
      res.send({
        data: {
          code: 200,
          msg: "验证成功",
          payload,
        },
      });
    }
  });
});

//token生成
router.post("/api/getToken", function (req, res) {
  //创建token码
  //jwt.sign(要加密的数据,秘钥)
  var data = {
    uname: "zhangsan",
    uage: 18,
    tidian: "xiu",
  };
  var mi = "sdsadsadadsagfghgh";

  var token = jwt.sign(data, mi, { expiresIn: 40 });

  console.log(token);
  res.send({
    data: {
      code: 1,
      msg: "token--ok",
      data: {
        token: token,
      },
    },
  });
});

//支付后状态
router.post("/api/successPayment", function (req, res) {
  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);

  //订单号
  let { out_trade_no, trade_no } = req.body;
  console.log(req.body);

  //支付宝配置
  //开始对接支付宝Api
  const formData = new AlipayFormData();
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod("get");
  //支付时的信息
  formData.addField("bizContent", {
    out_trade_no,
    trade_no,
  });
  //返回promise
  const result = alipaySdk.exec(
    // "alipay.trade.page.pay",//修改位下面
    "alipay.trade.query",
    {},
    { formData: formData }
  );

  //后端请求支付宝
  result.then((resData) => {
    axios({
      method: "GET",
      url: resData,
    })
      .then((data) => {
        let responseCode = data.data.alipay_trade_query_response;

        if (responseCode.code == "10000") {
          switch (responseCode.trade_status) {
            case "WAIT_BUYER-PAY":
              res.send({
                data: {
                  code: 0,
                  msg: "支付宝有交易记录，没付款",
                },
              });
              break;

            case "TRADE_CLOSED":
              res.send({
                data: {
                  code: 1,
                  msg: "交易关闭",
                },
              });
              break;

            case "TRADE_FINISHED":
              //修改订单状态
              //查询用户
              conection.query(
                `select * from user where tel = ${tokenObj.tel}`,
                function (error, results) {
                  //用户Id
                  let uId = results[0].id;
                  //查询订单Id
                  conection.query(
                    `select * from store_order where uId=${uId} and order_id = ${out_trade_no}`,
                    function (err, result) {
                      //得到订单Id
                      let id = result[0].id;
                      //修改订单状态2==》3
                      conection.query(
                        `update store_order set order_status = replace(order_status,'2','3') where id=${id}`,
                        function (e, r) {
                          res.send({
                            data: {
                              code: 2,
                              msg: "交易完成",
                            },
                          });
                        }
                      );
                    }
                  );
                }
              );

              break;

            case "TRADE_SUCCESS":
              //修改订单状态
              //查询用户
              conection.query(
                `select * from user where tel = ${tokenObj.tel}`,
                function (error, results) {
                  //用户Id
                  let uId = results[0].id;
                  //查询订单Id
                  conection.query(
                    `select * from store_order where uId=${uId} and order_id = ${out_trade_no}`,
                    function (err, result) {
                      //得到订单Id
                      let id = result[0].id;
                      //修改订单状态2==》3
                      conection.query(
                        `update store_order set order_status = replace(order_status,'2','3') where id=${id}`,
                        function (e, r) {
                          res.send({
                            data: {
                              code: 2,
                              msg: "交易完成",
                            },
                          });
                        }
                      );
                    }
                  );
                }
              );

              break;
          }
        } else if (responseCode.code == "40004") {
          res.send({
            data: {
              code: 4,
              msg: "交易不存在",
            },
          });
        }
      })
      .catch((err) => {
        res.send({
          data: {
            code: 500,
            msg: "交易失败",
            err,
          },
        });
      });
  });
});

//支付
router.post("/api/payment", function (req, res) {
  let { orderId, price, name } = req.body;

  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);

  //开始对接支付宝Api
  const formData = new AlipayFormData();
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod("get");
  //支付时的信息
  formData.addField("bizContent", {
    outTradeNo: orderId, //订单号
    productCode: "FAST_INSTANT_TRADE_PAY", //写死的
    totalAmount: price, //价格
    subject: name, //商品名称
    // body: '商品详情',//描述
  });
  //支付成功或失败要跳转的链接
  formData.addField("returnUrl", "http://localhost:8080/payment");
  //返回promise
  const result = alipaySdk.exec(
    "alipay.trade.page.pay",
    {},
    { formData: formData }
  );
  //对接支付宝成功，支付宝方法返回的数据
  result.then((resp) => {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: "支付中",
        paymentUrl: resp,
      },
    });
  });
});

//订单提交，修改订单状态
router.post("/api/submitOrder", function (req, res) {
  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);

  //订单号，购物车选中的商品id
  let { orderId, shopArr } = req.body;
  //查询用户
  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      //用户Id
      let uId = results[0].id;
      conection.query(
        `select * from store_order where uId = ${uId} and order_id = ${orderId}`,
        function (err, result) {
          //订单id
          let id = result[0].id;

          //修改订单状态
          conection.query(
            `update store_order set order_status = replace(order_status,'1','2') where id = ${id}`,
            function (e, r) {
              //购物车数据删除
              shopArr.forEach((v) => {
                //
                conection.query(
                  `delete from goods_cart where id = ${v}`,
                  function () {}
                );
              });
              res.send({
                data: {
                  code: 200,
                  success: true,
                  // msg:"订单提交，状态修改"
                },
              });
            }
          );
        }
      );
    }
  );
});

//查询订单
// router.post("/api/selectOrder",function(req, res){
router.post("/api/selectOrder", function (req, res) {
  //前端传的订单号
  let order_id = req.body.order_id;

  //查询订单信息
  conection.query(
    `select * from store_order where order_id = ${order_id}`,
    function (error, results) {
      if (error) throw error;

      res.send({
        data: {
          code: 200,
          success: true,
          msg: "成功",
          data: results,
        },
      });
    }
  );
});

//生成一个订单（订单号）
router.post("/api/addOrder", function (req, res) {
  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);
  //前端给后端的数据
  let goodsArr = req.body.arr;

  //生成订单order_id, 规则：时间戳+6位随机数
  function setTimeDateFmt(s) {
    //时间小于10秒，前位补零
    return s < 10 ? "0" + s : s;
  }
  function randomNumber() {
    //时间
    const now = new Date();

    let month = now.getMinutes() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();

    month = setTimeDateFmt(month);
    day = setTimeDateFmt(day);
    hour = setTimeDateFmt(hour);
    minutes = setTimeDateFmt(minutes);
    seconds = setTimeDateFmt(seconds);

    let orderCode =
      now.getFullYear().toString() +
      month.toString() +
      day +
      hour +
      minutes +
      seconds +
      Math.round(Math.random() * 1000000).toString();
    return orderCode;
  }

  /**
   * 未支付：1
   * 待支付：2
   * 支付成功：3
   * 支付失败：4|0
   */
  //商品名称列表
  let goodsName = [];
  //订单商品总金额
  let goodsPrice = 0;
  //订单商品总数
  let goodsNum = 0;
  //订单号,保存当前请求的订单数据
  let orderId = randomNumber();

  goodsArr.forEach((v) => {
    goodsName.push(v.goods_name);
    goodsPrice += v.goods_price * v.goods_num;
    goodsNum += parseInt(v.goods_num);
  });

  //拿到当前用户id
  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      let uId = results[0].id;

      //存储用户订单信息
      conection.query(
        `insert into store_order (order_id, goods_name, goods_price, goods_num, order_status, uId) values ('${orderId}','${goodsName}','${goodsPrice}', '${goodsNum}','1','${uId}')`,
        function (err, result) {
          //查询返回订单号
          conection.query(
            `select * from store_order where uId= ${uId} and order_id = ${orderId} `,
            function (err, result) {
              res.send({
                data: {
                  code: 200,
                  success: true,
                  msg: "订单已经生成",
                  data: result,
                  // data:result[0].order_id
                },
              });
            }
          );
        }
      );
    }
  );
});

//删除收货地址
router.post("/api/DeleteAddress", function (req, res) {
  //获取前端传递的收件地址Id
  let addressId = req.body.id;

  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);
  conection.query(
    `select * from user where  tel = ${tokenObj.tel}`,
    function (error, results) {
      let uId = results[0].id;

      conection.query(
        `delete from address where id=${addressId} and uId=${uId}`,
        function (err, result) {
          res.send({
            data: {
              code: 200,
              success: true,
              msg: "地址删除成功",
            },
          });
        }
      );
    }
  );
});

//修改收货地址
router.post("/api/UpdataAddress", function (req, res) {
  let {
    id,
    name,
    tel,
    country,
    province,
    city,
    county,
    areaCode,
    postalCode,
    addressDetail,
    isDefault,
  } = req.body;

  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);

  //查询用户，获取用户id
  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      //得到用户id
      let uId = results[0].id;

      //查询当前发 有 或 没有 默认收货地址isDefault=1、
      conection.query(
        `select * from address where uId=${uId} and isDefault=${isDefault}`,
        function (err, result) {
          if (err) throw err;

          if (result.length > 0) {
            //有默认地址
            //获取当前地址的id
            let addressId = result[0].id;
            //默认不管是否为1，都设置为0
            conection.query(
              `update address set isDefault = replace(isDefault,'1','0') where id = ${addressId}`,
              function (er, re) {
                let updataSql = `update address set uId=?,name=?, tel=?, country=?, province=?, city=?, county=?, areaCode=?, postalCode=?, addressDetail=?, isDefault=? where id = ${id} `;

                conection.query(
                  updataSql,
                  [
                    uId,
                    name,
                    tel,
                    country,
                    province,
                    city,
                    county,
                    areaCode,
                    postalCode,
                    addressDetail,
                    isDefault,
                  ],
                  function (e, r) {
                    res.send({
                      data: {
                        code: 200,
                        success: true,
                        msg: "修改地址信息成功",
                      },
                    });
                  }
                );
              }
            );
          } else {
            //没有默认地址
            let updataSql = `update address set uId=?,name=?, tel=?, country=?, province=?, city=?, county=?, areaCode=?, postalCode=?, addressDetail=?, isDefault=? where id = ${id} `;

            conection.query(
              updataSql,
              [
                uId,
                name,
                tel,
                country,
                province,
                city,
                county,
                areaCode,
                postalCode,
                addressDetail,
                isDefault,
              ],
              function (e, r) {
                res.send({
                  data: {
                    code: 200,
                    success: true,
                    msg: "修改地址信息成功",
                  },
                });
              }
            );
          }
        }
      );
    }
  );
});

//查询所有地址
router.post("/api/selectAddress", function (req, res) {
  //获取前端的用户token
  let token = req.headers.token;
  //解析token
  let tokenObj = jwt.decode(token);

  //查询用户，获取用户id
  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      //得到用户id
      let uId = results[0].id;

      //查询当前id下的地址
      conection.query(
        `select * from address where uId = ${uId}`,
        function (err, result) {
          if (err) throw err;

          res.send({
            data: {
              code: 200,
              success: true,
              smg: "获取所有地址成功",
              data: result,
            },
          });
        }
      );
    }
  );
});

//存储地址
router.post("/api/AddAddress", function (req, res) {
  let {
    name,
    tel,
    country,
    province,
    city,
    county,
    areaCode,
    postalCode,
    addressDetail,
    isDefault,
  } = req.body;

  //当前用户的token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  // 查询用户
  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      //获取用户ID
      let uId = results[0].id;
      //增加地址
      //判断默认地址 isDefault
      if (isDefault != 1) {
        //如果默认值不为 1，直接添加。
        conection.query(
          `insert into address (uId, name, tel, country, province, city, county, areaCode, postalCode, addressDetail, isDefault) values ('${uId}', '${name}', '${tel}', '${country}', '${province}', '${city}', '${county}', '${areaCode}', '${postalCode}', '${addressDetail}', '${isDefault}')`,
          function (err, result) {
            if (err) throw err;

            res.send({
              data: {
                code: 200,
                success: true,
                msg: "收货地址添加成功",
              },
            });
          }
        );
      } else {
        //默认值为1，将其他的isDefault设置为0
        conection.query(
          `select * from address where uId = ${uId} and isDefault = ${isDefault}`,
          function (er, resul) {
            if (er) throw er;

            //如果地址数据中没有默的（isDefault ==1）的数据时直接添加数据
            if (resul.length == 0) {
              //没有isDefault = 1 的哪条数据，直接添加
              conection.query(
                `insert into address (uId, name, tel, country, province, city, county, areaCode, postalCode, addressDetail, isDefault) values ('${uId}', '${name}', '${tel}', '${country}', '${province}', '${city}', '${county}', '${areaCode}', '${postalCode}', '${addressDetail}', '${isDefault}')`,
                function (e, r) {
                  if (e) throw e;

                  res.send({
                    data: {
                      code: 200,
                      success: true,
                      msg: "收货地址添加成功",
                    },
                  });
                }
              );
            } else {
              let addressId = resul[0].id;
              conection.query(
                `update address set isDefault = replace(isDefault,'1','0') where id = ${addressId}`,
                function () {
                  conection.query(
                    `insert into address (uId, name, tel, country, province, city, county, areaCode, postalCode, addressDetail, isDefault) values ('${uId}', '${name}', '${tel}', '${country}', '${province}', '${city}', '${county}', '${areaCode}', '${postalCode}', '${addressDetail}', '${isDefault}')`,
                    function (e, r) {
                      if (e) throw e;

                      res.send({
                        data: {
                          code: 200,
                          success: true,
                          msg: "收货地址添加成功",
                        },
                      });
                    }
                  );
                }
              );
            }
          }
        );
      }
    }
  );
});

//修改当前购物车数量
router.post("/api/updateNum", function (req, res) {
  let { id, changeNum } = req.body;

  //查到当前商品
  conection.query(
    `select * from goods_cart where id = ${id}`,
    function (error, results) {
      if (error) throw error;

      //原来的数量
      let num = results[0].goods_num;

      //查询修改当前购物车数量
      conection.query(
        `update goods_cart set goods_num = replace(goods_num, ${num},${changeNum}) where id=${id}`,
        function (err, result) {
          if (err) throw err;

          res.send({
            data: {
              code: 200,
              success: true,
              msg: "修改成功",
            },
          });
        }
      );
    }
  );
});

//删除购物车数据
router.post("/api/deleteCart", function (req, res) {
  let arrId = req.body.arrId;

  for (let i = 0; i < arrId.length; i++) {
    //删除
    conection.query(
      `delete from goods_cart where id = ${arrId[i]}`,
      function (error, results) {
        if (error) throw error;

        //返回购物车数据
        conection.query("select * from goods_cart", function (err, result) {
          if (err) throw err;

          res.send({
            data: {
              code: 200,
              success: true,
              msg: "删除成功",
              data: result,
            },
          });
        });
      }
    );
  }
});

//查询当前用户的购物车数据
router.post("/api/selectCart", function (req, res) {
  //当前用户的token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //口令(密钥)
  let secret = "xxxccc445sdf##";

  let dataToken = {
    token: token,
    secret: secret,
  };

  // console.log("token",token)
  // console.log("tokenObj",tokenObj)

  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      let token = results[0].token;

      jwt.verify(token, secret, (err, payload) => {
        if (err) {
          console.log("geterr:", err);
          res.send({
            data: {
              code: 1000,
              msg: `token过期了:${err}`,
            },
          });
        } else {
          //false 未过期
          //查询user表的对应用户
          conection.query(
            ` select * from user where tel = ${tokenObj.tel} `,
            function (error, results) {
              if (error) throw error;
              //用户id
              let uId = results[0].id;
              //查询购物车
              conection.query(
                `select * from goods_cart where uId = ${uId}`,
                function (err, result) {
                  if (err) throw err;

                  res.send({
                    data: {
                      code: 200,
                      success: 200,
                      data: result,
                    },
                  });
                }
              );
            }
          );
        }
      });
    }
  );
});

//购物车添加
router.post("/api/addCart", function (req, res) {
  //后端接收前端的参数
  let goodsId = req.body.goodsId;

  //后端通过前端传递过来的token，解析得到相应的用户信息
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  let secret = "xxxccc445sdf##";
  console.log("token", token);
  let dataToken = {
    token: token,
    secret: secret,
  };

  conection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      let token = results[0].token;
      jwt.verify(token, secret, (err, payload) => {
        if (err) {
          console.log("geterr:", err);
          res.send({
            data: {
              code: 1000,
              msg: `token过期了:${err}`,
            },
          });
        } else {
          //查询user表的对应用户
          conection.query(
            ` select * from user where tel = ${tokenObj.tel} `,
            function (error, results) {
              if (error) throw error;
              //用户id
              let uId = results[0].id;
              //查询商品
              conection.query(
                `select * from goods_list where id=${goodsId}`,
                function (err, results) {
                  if (err) throw err;
                  let goodsName = results[0].name;
                  let goodsPrice = results[0].price;
                  let goodsImgUrl = results[0].imgUrl;

                  //查询当前用户在之前是否添加过本商品
                  conection.query(
                    `select * from goods_cart where uId = ${uId}  and goods_id = ${goodsId}`,
                    function (e, r) {
                      if (e) throw e;

                      if (r.length > 0) {
                        //用户之前已经添加过商品到购物车
                        let num = r[0].goods_num;
                        conection.query(
                          `update goods_cart set goods_num = replace(goods_num, ${num},${
                            parseInt(num) + 1
                          }) where id=${r[0].id}`,
                          function (or, re) {
                            if (or) throw or;

                            res.send({
                              code: 200,
                              data: {
                                success: true,
                                msg: "又添加一个商品",
                              },
                            });
                          }
                        );
                      } else {
                        //没添加过购物车
                        //新增购物车信息
                        conection.query(
                          `insert into goods_cart (uId, goods_id, goods_name, goods_price, goods_num, goods_imgUrl) value ('${uId}','${goodsId}','${goodsName}',' ${goodsPrice}','1','${goodsImgUrl}')`,
                          function (erro, results) {
                            if (erro) throw erro;

                            res.send({
                              code: 200,
                              data: {
                                success: true,
                                msg: "添加成功",
                              },
                            });
                          }
                        );
                      }
                    }
                  );
                }
              );
            }
          );
        }
      });
    }
  );
});

//修改密码
router.post("/api/recovery", function (req, res) {
  let params = {
    userTel: req.body.userTel,
    userPwd: req.body.userPwd,
  };
  //查询用户是否存在
  conection.query(user.queryUserTel(params), function (error, results) {
    if (error) return;
    //某一条记录的id，用以查询目标
    let id = results[0].id;
    let pwd = results[0].pwd;
    conection.query(
      `update user set pwd = replace(pwd,'${pwd}', '${params.userPwd}') where id = ${id} `,
      function (err, result) {
        if (err) throw err;

        res.send({
          code: 0,
          data: {
            success: true,
            msg: "修改成功",
          },
        });
      }
    );
  });
});

//查询用户是否存在
router.post("/api/selectUser", function (req, res) {
  let params = {
    userTel: req.body.userTel,
  };

  //查询用户是否存在
  conection.query(user.queryUserTel(params), function (error, result) {
    if (error) throw error;
    if (result.length > 0) {
      res.send({
        code: 200,
        data: {
          success: true,
          msg: "验证成功",
        },
      });
    } else {
      res.send({
        code: 0,
        data: {
          success: false,
          msg: "此用户不存在",
        },
      });
    }
  });
});

//注册用户
router.post("/api/register", function (req, res) {
  let params = {
    userTel: req.body.userTel,
    userPwd: req.body.userPwd,
  };

  //查询用户是否存在
  conection.query(user.queryUserTel(params), function (error, result) {
    if (error) throw error;
    if (result.length > 0) {
      //用户存在
      res.send({
        code: 200,
        data: {
          success: true,
          msg: "用户已经注册",
          data: result[0],
        },
      });
    } else {
      //不存在，新增用户
      conection.query(user.inserData(params), function (error, result) {
        if (error) throw error;
        //新增完成，在查询数据返回给前端
        conection.query(user.queryUserTel(params), function (error, result) {
          if (error) throw error;

          //返回数据
          res.send({
            code: 200,
            data: {
              success: true,
              msg: "注册成功",
              data: result[0],
            },
          });
        });
      });
    }
  });
});

//添加一个用户
router.post("/api/addUser", function (req, res) {
  //获取前端的数据
  let params = {
    userTel: req.body.userTel,
  };
  //查询用户是否存在
  conection.query(user.queryUserTel(params), function (error, result) {
    if (error) throw error;
    if (result.length > 0) {
      //用户存在
      res.send({
        code: 200,
        data: {
          success: true,
          msg: "登录成功",
          data: result[0],
        },
      });
    } else {
      //不存在，新增用户
      conection.query(user.inserData(params), function (error, result) {
        if (error) throw error;
        //新增完成，在查询数据返回给前端
        conection.query(user.queryUserTel(params), function (error, result) {
          if (error) throw error;

          //返回数据
          res.send({
            code: 200,
            data: {
              success: true,
              msg: "登录成功",
              data: result[0],
            },
          });
        });
      });
    }
  });
});

//发送短信验证码
router.post("/api/code", function (req, res) {
  let tel = req.body.userTel;

  //  //验证码相关
  //  // 短信应用SDK AppID
  //   var appid = 1400187558;  // SDK AppID是1400开头

  //   // 短信应用SDK AppKey
  //   var appkey = "dc9dc3391896235ddc2325685047edc7";

  //   // 需要发送短信的手机号码
  //   var phoneNumbers = [tel];

  //   // 短信模板ID，需要在短信应用中申请
  //   var templateId = 285590;  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

  //   // 签名
  //   var smsSign = "三人行慕课";  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

  //   // 实例化QcloudSms
  //   var qcloudsms = QcloudSms(appid, appkey);

  //   // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  //   function callback(err, ress, resData) {
  //       if (err) {
  //           console.log("err: ", err);
  //       } else {
  //          res.send({
  //           code:200,
  //           data:{
  //             success:true,
  //             data:ress.req.body.params[0]
  //           }
  //          })
  //       }
  //   }

  //验证码相关
  // 短信应用SDK AppID
  var appid = 1400702960; // SDK AppID是1400开头

  // 短信应用SDK AppKey
  var appkey = "3b73700ce31d66a96a6acab76efdd1ff";

  // 需要发送短信的手机号码
  var phoneNumbers = [tel];

  // 短信模板ID，需要在短信应用中申请
  var templateId = 1467539; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

  // 签名
  var smsSign = "trygoI"; // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

  // 实例化QcloudSms
  var qcloudsms = QcloudSms(appid, appkey);

  // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  function callback(err, ress, resData) {
    if (err) {
      console.log("err: ", err);
    } else {
      res.send({
        code: 200,
        data: {
          success: true,
          data: ress.req.body.params[0],
        },
      });
    }
  }

  //指定模板ID单发短信
  var ssender = qcloudsms.SmsSingleSender();
  //这个变量就是 往手机上发送的短信
  var params = [Math.floor(Math.random() * (9999 - 1000)) + 1000];
  ssender.sendWithParam(
    86,
    phoneNumbers[0],
    templateId,
    params,
    smsSign,
    "",
    "",
    callback
  ); // 签名参数不能为空串
});

//查询商品数据接口
router.get("/api/goods/shopList", function (req, res) {
  // let searchName = req.query.searchName;
  let [searchName, orderName] = Object.keys(req.query);
  let [name, order] = Object.values(req.query);

  //查询数据库中的某个表（goods_liat）；模糊查询‘like "% +search+ %"’
  conection.query(
    'select * from goods_list where name like "%' +
      name +
      '%" order by ' +
      orderName +
      " " +
      order +
      "",
    function (error, results) {
      res.send({
        code: 0,
        data: results,
      });
    }
  );
});

//根据id查询商品的接口
router.get("/api/goods/id", function (req, res) {
  let id = req.query.id;

  conection.query(
    "select * from goods_list where id=" + id + " ",
    function (error, results) {
      if (error) throw error;
      res.json({
        code: 0,
        data: results,
      });
    }
  );
});

//验证用户登录信息
router.post("/api/login", function (req, res) {
  //后端要接收前端传递过来的值
  let params = {
    userTel: req.body.userTel,
    userPwd: req.body.userPwd,
  };

  //登录再更新一次token目的，更新过期时间
  let userTel = params.userTel;
  let userPwd = params.userPwd || "666666";
  //引入jwt Token包
  const jwt = require("jsonwebtoken");
  //用户信息
  let payload = { tel: userTel };
  //口令(密钥)
  let secret = "xxxccc445sdf##";
  //生成token
  let token = jwt.sign(payload, secret, { expiresIn: 120 });

  // console.log("jwt.decode",jwt.decode(token))

  //查询用户手机号是否存在
  conection.query(user.queryUserTel(params), function (error, results) {
    //手机号码存在
    if (results.length > 0) {
      //记录的id
      let id = results[0].id;

      conection.query(user.queryUserPwd(params), function (err, result) {
        //手机密码存在
        if (result.length > 0) {
          conection.query(
            `update user set token = '${token}' where id = ${id}`,
            function (e, r) {
              //手机号码和密码都正确
              res.send({
                code: 200,
                data: {
                  success: true,
                  data: results[0],
                  msg: "密码正确",
                },
              });
            }
          );
        } else {
          //密码不存在
          res.send({
            code: 302,
            data: {
              success: false,
              msg: "密码不正确",
            },
          });
        }
      });
    } else {
      //手机号码不存在
      res.send({
        code: 301,
        data: {
          success: false,
          msg: "手机号未注册",
        },
      });
    }
  });
});

//首页推荐数据
router.get("/api/index_list/0/data/1", function (req, res) {
  res.send({
    code: 0,
    data: {
      topBar: [
        { id: 0, value: 0, label: "推荐" },
        { id: 1, value: 1, label: "大红袍" },
        { id: 2, value: 2, label: "铁观音" },
        { id: 3, value: 3, label: "绿茶" },
        { id: 4, value: 4, label: "普尔" },
        { id: 5, value: 5, label: "茶具" },
        { id: 6, value: 6, label: "推荐" },
        { id: 7, value: 7, label: "花茶" },
      ],

      data: [
        //swiper
        {
          id: 0,
          type: "swiperList",
          data: [
            {
              id: 1,
              imgUrl:
                "https://img.tea7.com/0166434_0.jpeg?x-oss-process=image/resize,w_720",
            },
            {
              id: 2,
              imgUrl:
                "https://img.tea7.com/0169413_0.jpeg?x-oss-process=image/resize,w_720",
            },
            {
              id: 3,
              imgUrl:
                "https://img.tea7.com/0169412_0.jpeg?x-oss-process=image/resize,w_720",
            },
          ],
        },

        //icons
        {
          id: 1,
          type: "iconsList",
          data: [
            {
              id: 1,
              title: "自饮茶",
              imgUrl: "https://imgcon.tea7.com/6363743876200428263577206.png",
            },
            {
              id: 2,
              title: "茶具",
              imgUrl: "https://imgcon.tea7.com/6363743876136364412448843.png",
            },
            {
              id: 3,
              title: "茶礼盒",
              imgUrl: "https://imgcon.tea7.com/6363743876164490164235224.png",
            },
            {
              id: 4,
              title: "领福利",
              imgUrl: "https://imgcon.tea7.com/6363743876147303652949610.png",
            },
            {
              id: 5,
              title: "官方验证",
              imgUrl: "https://imgcon.tea7.com/6366085324327706652770939.png",
            },
          ],
        },

        //爆款推荐
        {
          id: 2,
          type: "recommendList",
          data: [
            {
              id: 1,
              name: "凤庆滇红大金针红茶",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img.tea7.com/0160224_0.png?x-oss-process=image/resize,w_300",
            },
            {
              id: 2,
              name: "龙井1号铁罐250g",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img11.360buyimg.com/n1/jfs/t1/59221/6/16904/205704/60ef96d1Ed0f20158/53bc8dff37c4b39f.jpg",
            },
            {
              id: 3,
              name: "黄山太平猴魁绿茶1号",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img.tea7.com/0170763_0.png?x-oss-process=image/resize,w_300",
            },
            {
              id: 4,
              name: "凤庆滇红大金针红茶",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img.tea7.com/0160224_0.png?x-oss-process=image/resize,w_300",
            },
            {
              id: 5,
              name: "龙井1号铁罐250g",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img11.360buyimg.com/n1/jfs/t1/59221/6/16904/205704/60ef96d1Ed0f20158/53bc8dff37c4b39f.jpg",
            },
            {
              id: 6,
              name: "黄山太平猴魁绿茶1号",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img.tea7.com/0170763_0.png?x-oss-process=image/resize,w_300",
            },
            {
              id: 7,
              name: "凤庆滇红大金针红茶",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img.tea7.com/0160224_0.png?x-oss-process=image/resize,w_300",
            },
            {
              id: 8,
              name: "龙井1号铁罐250g",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img11.360buyimg.com/n1/jfs/t1/59221/6/16904/205704/60ef96d1Ed0f20158/53bc8dff37c4b39f.jpg",
            },
            {
              id: 9,
              name: "黄山太平猴魁绿茶1号",
              content: "新鲜爽口 口粮首选",
              price: "68",
              imgUrl:
                "	https://img.tea7.com/0170763_0.png?x-oss-process=image/resize,w_300",
            },
          ],
        },

        //猜你喜欢
        {
          id: 3,
          type: "likeList",
          data: [
            {
              id: 18,
              imgUrl:
                "https://img14.360buyimg.com/n7/jfs/t1/150916/39/23629/523098/61cd5b4fE8265ae95/5e2adbf328849569.jpg",
              name: "建盏茶具套装 红色芝麻毫 12件套",
              price: "399",
            },
            {
              id: 19,
              imgUrl:
                "https://img13.360buyimg.com/n7/jfs/t1/23064/25/16165/218883/6273a06fEb5c58940/1c55e26c3cacfc93.jpg",
              name: "建盏茶具套装 雀蓝芝麻毫 12件套",
              price: "299",
            },
            {
              id: 20,
              imgUrl:
                "https://img13.360buyimg.com/n7/jfs/t1/98204/10/18226/345735/614aa29cEeb503221/0156267728ed869c.jpg",
              name: "建盏茶具套装 紫黑芝麻毫 12件套",
              price: "399",
            },
            {
              id: 21,
              imgUrl:
                "https://img11.360buyimg.com/n7/jfs/t1/87697/25/27314/187192/625e6f37E824e6225/433c4e97f2946834.jpg",
              name: "建盏茶具套装 雀眼芝麻毫 12件套",
              price: "299",
            },
            {
              id: 22,
              imgUrl:
                "https://img11.360buyimg.com/n7/jfs/t1/161452/19/3477/144504/600670b5E6d111a20/d49211efa9eabf08.jpg",
              name: "建盏茶具套装 铀黄芝麻毫 12件套",
              price: "399",
            },
            {
              id: 23,
              imgUrl:
                "https://img14.360buyimg.com/n7/jfs/t1/150916/39/23629/523098/61cd5b4fE8265ae95/5e2adbf328849569.jpg",
              name: "建盏茶具套装 彩绘红色芝麻毫 12件套",
              price: "299",
            },
            {
              id: 24,
              imgUrl:
                "https://img13.360buyimg.com/n7/jfs/t1/23064/25/16165/218883/6273a06fEb5c58940/1c55e26c3cacfc93.jpg",
              name: "建盏茶具套装 紫黑芝麻毫 12件套",
              price: "399",
            },
            {
              id: 25,
              imgUrl:
                "https://img13.360buyimg.com/n7/jfs/t1/98204/10/18226/345735/614aa29cEeb503221/0156267728ed869c.jpg",
              name: "建盏茶具套装 雀眼芝麻毫 12件套",
              price: "299",
            },
            {
              id: 26,
              imgUrl:
                "https://img11.360buyimg.com/n7/jfs/t1/87697/25/27314/187192/625e6f37E824e6225/433c4e97f2946834.jpg",
              name: "建盏茶具套装 铀黄芝麻毫 12件套",
              price: "399",
            },
            {
              id: 27,
              imgUrl:
                "https://img11.360buyimg.com/n7/jfs/t1/161452/19/3477/144504/600670b5E6d111a20/d49211efa9eabf08.jpg",
              name: "建盏茶具套装 红色芝麻毫 12件套",
              price: "299",
            },
          ],
        },
      ],
    },
  });
});

//大红袍数据
router.get("/api/index_list/1/data/1", function (req, res) {
  res.send({
    code: 0,
    data: [
      {
        id: 1,
        type: "adList",
        data: [
          {
            id: 1,
            imgUrl: "https://imgcon.tea7.com/6363865086046441694910085.jpg",
          },
          {
            id: 2,
            imgUrl: "https://imgcon.tea7.com/6363865086046441694910085.jpg",
          },
        ],
      },
      //猜你喜欢
      {
        id: 2,
        type: "likeList",
        data: [
          {
            id: 1,
            imgUrl:
              "https://img14.360buyimg.com/n7/jfs/t1/150916/39/23629/523098/61cd5b4fE8265ae95/5e2adbf328849569.jpg",
            name: "建盏茶具套装 红色芝麻毫 12件套",
            price: "299",
          },
          {
            id: 2,
            imgUrl:
              "https://img13.360buyimg.com/n7/jfs/t1/23064/25/16165/218883/6273a06fEb5c58940/1c55e26c3cacfc93.jpg",
            name: "建盏茶具套装 红色芝麻毫 12件套",
            price: "399",
          },
          {
            id: 3,
            imgUrl:
              "https://img13.360buyimg.com/n7/jfs/t1/98204/10/18226/345735/614aa29cEeb503221/0156267728ed869c.jpg",
            name: "建盏茶具套装 红色芝麻毫 12件套",
            price: "299",
          },
          {
            id: 4,
            imgUrl:
              "https://img11.360buyimg.com/n7/jfs/t1/87697/25/27314/187192/625e6f37E824e6225/433c4e97f2946834.jpg",
            name: "建盏茶具套装 红色芝麻毫 12件套",
            price: "399",
          },
          {
            id: 5,
            imgUrl:
              "https://img11.360buyimg.com/n7/jfs/t1/161452/19/3477/144504/600670b5E6d111a20/d49211efa9eabf08.jpg",
            name: "建盏茶具套装 红色芝麻毫 12件套",
            price: "299",
          },
        ],
      },
    ],
  });
});

//分类部分的请求
router.get("/api/goods/list", function (req, res) {
  res.send({
    code: 0,
    data: [
      {
        //一级
        id: 0,
        name: "推荐",
        data: [
          {
            //二级
            id: 0,
            name: "推荐",
            list: [
              //三级
              {
                id: 0,
                name: "紫砂壶",
                imgUrl:
                  "https://img.tea7.com/0011478_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "铁观音",
                imgUrl:
                  "https://img.tea7.com/0011446_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 2,
                name: "金骏眉",
                imgUrl:
                  "https://img.tea7.com/0011372_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 3,
                name: "武夷岩茶",
                imgUrl:
                  "https://img.tea7.com/0011447_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 4,
                name: "龙井",
                imgUrl:
                  "https://img.tea7.com/0011479_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 5,
                name: "云南滇红",
                imgUrl:
                  "https://img.tea7.com/0011450_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 6,
                name: "建盏",
                imgUrl:
                  "https://img.tea7.com/0011239_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 7,
                name: "功夫茶具",
                imgUrl:
                  "https://img.tea7.com/0011471_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 1,
        name: "绿茶",
        data: [
          {
            //二级
            id: 0,
            name: "绿茶",
            list: [
              //三级
              {
                id: 0,
                name: "龙井",
                imgUrl:
                  "https://img.tea7.com/0011479_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "黄山毛峰",
                imgUrl:
                  "https://img.tea7.com/0011444_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 2,
                name: "碧螺春",
                imgUrl:
                  "https://img.tea7.com/0011445_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 3,
                name: "雀舌",
                imgUrl:
                  "https://img.tea7.com/0153803_0.png?x-oss-process=image/resize,w_150",
              },
              {
                id: 4,
                name: "太平猴魁",
                imgUrl:
                  "https://img.tea7.com/0034477_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 5,
                name: "珍稀白茶",
                imgUrl:
                  "https://img.tea7.com/0057822_0.png?x-oss-process=image/resize,w_150",
              },
              {
                id: 6,
                name: "六安瓜片",
                imgUrl:
                  "https://img.tea7.com/0153804_0.png?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 2,
        name: "乌龙",
        data: [
          {
            //二级
            id: 0,
            name: "乌龙",
            list: [
              //三级
              {
                id: 0,
                name: "咏春佛手",
                imgUrl:
                  "https://img.tea7.com/0165422_0.png?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "铁观音",
                imgUrl:
                  "https://img.tea7.com/0011446_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 2,
                name: "武夷岩茶",
                imgUrl:
                  "https://img.tea7.com/0011447_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 3,
                name: "漳平水仙",
                imgUrl:
                  "https://img.tea7.com/0011448_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 3,
        name: "红茶",
        data: [
          {
            //二级
            id: 0,
            name: "红茶",
            list: [
              //三级
              {
                id: 0,
                name: "英德红茶",
                imgUrl:
                  "https://img.tea7.com/0167288_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "坦洋工夫",
                imgUrl:
                  "https://img.tea7.com/0167289_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 2,
                name: "金骏眉",
                imgUrl:
                  "https://img.tea7.com/0011372_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 3,
                name: "正山小种",
                imgUrl:
                  "https://img.tea7.com/0011449_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 4,
        name: "普洱",
        data: [
          {
            //二级
            id: 0,
            name: "普洱",
            list: [
              //三级
              {
                id: 0,
                name: "生茶",
                imgUrl:
                  "https://img.tea7.com/0011457_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "熟茶",
                imgUrl:
                  "https://img.tea7.com/0011458_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 5,
        name: "白茶",
        data: [
          {
            //二级
            id: 0,
            name: "白茶",
            list: [
              //三级
              {
                id: 0,
                name: "白牡丹",
                imgUrl:
                  "https://img.tea7.com/0011455_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "牡丹王",
                imgUrl:
                  "https://img.tea7.com/0011469_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 2,
                name: "白毫根针",
                imgUrl:
                  "https://img.tea7.com/0011456_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 3,
                name: "寿眉",
                imgUrl:
                  "https://img.tea7.com/0011454_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 6,
        name: "花茶",
        data: [
          {
            //二级
            id: 0,
            name: "花茶",
            list: [
              //三级
              {
                id: 0,
                name: "茉莉花茶",
                imgUrl:
                  "https://img.tea7.com/0011459_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 7,
        name: "茶具",
        data: [
          {
            //二级
            id: 0,
            name: "茶具",
            list: [
              //三级
              {
                id: 0,
                name: "茶宠",
                imgUrl:
                  "https://img.tea7.com/0170082_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 1,
                name: "紫砂壶",
                imgUrl:
                  "https://img.tea7.com/0011478_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 2,
                name: "建盏",
                imgUrl:
                  "https://img.tea7.com/0011239_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 3,
                name: "功夫茶具",
                imgUrl:
                  "https://img.tea7.com/0011471_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 4,
                name: "茶具配件",
                imgUrl:
                  "	https://img.tea7.com/0011473_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 5,
                name: "主人杯",
                imgUrl:
                  "https://img.tea7.com/0167779_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 6,
                name: "干泡茶具",
                imgUrl:
                  "https://img.tea7.com/0012391_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 7,
                name: "旅行茶具",
                imgUrl:
                  "https://img.tea7.com/0011475_0.jpeg?x-oss-process=image/resize,w_150",
              },
              {
                id: 8,
                name: "整套茶具",
                imgUrl:
                  "https://img.tea7.com/0011475_0.jpeg?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
      {
        //一级
        id: 8,
        name: "手艺",
        data: [
          {
            //二级
            id: 0,
            name: "手艺",
            list: [
              //三级
              {
                id: 0,
                name: "根雕",
                imgUrl:
                  "https://img.tea7.com/0011240_0.png?x-oss-process=image/resize,w_150",
              },
            ],
          },
        ],
      },
    ],
  });
});
module.exports = router;
